#include "gt_circular_list.h"

// ok
gt_circular_list *create_circular_list(int size) {
  gt_circular_list *lst =
      (gt_circular_list *)calloc(1, sizeof(gt_circular_list));

  lst->size = size;
  lst->nb_element = 0;
  lst->head = NULL;

  return lst;
}

// ok
void add_circular_element(gt_circular_list **list, char *element) {
  list_element *new_elem;
  list_element *pointer_element;
  int len = strlen(element) + 1;

  new_elem = (list_element *)calloc(1, sizeof(list_element) + len);
  strncpy(new_elem->data, element, len);
  new_elem->next = NULL;

  if ((*list)->nb_element == 0) {
    (*list)->head = new_elem;
    (*list)->nb_element++;

    return;
  }

  pointer_element = (*list)->head;
  while (pointer_element->next)
    pointer_element = pointer_element->next;

  pointer_element->next = new_elem;

  if ((*list)->nb_element < (*list)->size)
    (*list)->nb_element++;
  else {
    list_element *old_head = (*list)->head;
    (*list)->head = (*list)->head->next;
    free(old_head);
  }
}

// ok
void free_circular_list(gt_circular_list **list) {
  list_element *elem = (*list)->head;

  while (elem->next) {
    list_element *old_element = elem;
    elem = elem->next;
    free(old_element);
  }

  free(elem);
}